<script setup>
import { ref, computed, watch } from 'vue'
import BaseChart from '@/components/chart/BaseChart.vue'
import CustomDateRadio from '@/components/header/CustomDateRadio.vue'
import { useCompanyStore } from '@/stores/company'
import { getAllSubCategoryReportApi, getSubCategoryReportApi } from '@/api/category'
import { handleError } from '@/utils/handleError'
import dayjs from 'dayjs'

const props = defineProps({
    title: {
        type: String,
        default: '用途用电趋势'
    },
    height: {
        type: String,
        default: '230px'
    }
})

const companyStore = useCompanyStore()
const selectedSubCategory = ref(null)
const chartTimeRange = ref(null)
const chartData = ref([])
const rankingChartData = ref([])
const chartLoading = ref(false)

// 获取用途总数据
async function getSubCategoryTotalData(start_time, end_time) {
    if (!start_time || !end_time) return null

    if (!companyStore?.currentCompany?.id) {
        console.warn('当前公司ID不存在');
        return null;
    }

    try {
        let res = await getAllSubCategoryReportApi({
            id: companyStore.currentCompany.id,
            start_time,
            end_time,
            type: 2,
        })

        if (!res || !res.aggregated_data) {
            console.warn('获取用途数据返回格式不正确:', res);
            return null;
        }

        return res.aggregated_data
    } catch (error) {
        handleError(error, '获取用途数据失败')
        return null
    }
}

// 获取单个用途趋势数据
async function getSubCategoryData() {
    if (!selectedSubCategory.value || !chartTimeRange.value) return

    if (!companyStore?.currentCompany?.id) {
        console.warn('当前公司ID不存在');
        return;
    }

    chartLoading.value = true
    try {
        let res = await getSubCategoryReportApi({
            id: companyStore.currentCompany.id,
            sub_category: selectedSubCategory.value,
            ...chartTimeRange.value,
            type: 2
        })

        if (!res?.aggregated_data) {
            console.warn('趋势图数据返回格式不正确:', res);
            chartData.value = []
            return
        }

        const aggregatedData = Array.isArray(res.aggregated_data) ? res.aggregated_data : [];

        chartData.value = aggregatedData
            .filter((item) => Array.isArray(item) && item.length > 0)
            .map(item => {
                let formatStr = 'YYYY-MM-DD'
                switch (chartTimeRange.value?.interval) {
                    case 'day':
                        formatStr = 'MM-DD'
                        break
                    case 'month':
                        formatStr = 'YYYY-MM'
                        break
                    case 'year':
                        formatStr = 'YYYY'
                        break
                    case 'quarter':
                        formatStr = 'Q季度'
                        break
                }

                const startTime = item[0]?.StartTime
                const value = item.reduce((acc, cur) => {
                    const used = cur && typeof cur.Used !== 'undefined' ? Number(cur.Used) : 0;
                    return acc + used;
                }, 0).toFixed(2)

                return {
                    time: startTime ? dayjs(startTime).format(formatStr) : '-',
                    timestamp: startTime ? dayjs(startTime).valueOf() : 0,
                    value: value
                }
            })
            .sort((a, b) => a.timestamp - b.timestamp)
    } catch (error) {
        handleError(error, '获取趋势图数据失败')
        chartData.value = []
    } finally {
        chartLoading.value = false
    }
}

// 获取排名数据
async function fetchRankingData() {
    if (!chartTimeRange.value) return

    try {
        let data = await getSubCategoryTotalData(chartTimeRange.value.start_time, chartTimeRange.value.end_time)
        if (data) {
            if (!Array.isArray(data)) {
                console.warn('排名数据格式不正确, 期望数组但收到:', typeof data);
                rankingChartData.value = [];
                return;
            }

            rankingChartData.value = data.flat()
                .map(item => {
                    if (!item) return null;
                    const usage = Array.isArray(item.usage) ? item.usage : [];
                    return {
                        name: item.subcategory || '其他',
                        value: usage.reduce((acc, meter) => {
                            const used = meter && typeof meter.Used !== 'undefined' ? Number(meter.Used) : 0;
                            return acc + used;
                        }, 0),
                        subcategory: item.subcategory
                    };
                })
                .filter(item => item !== null && item.value > 0)
                .sort((a, b) => b.value - a.value)

            if (rankingChartData.value.length > 0 && !selectedSubCategory.value) {
                selectedSubCategory.value = rankingChartData.value[0].subcategory
            }
        } else {
            rankingChartData.value = [];
        }
    } catch (error) {
        handleError(error, '获取排名数据失败')
        rankingChartData.value = [];
    }
}

// 重置组件状态
function resetComponentState() {
    selectedSubCategory.value = null
    chartData.value = []
    rankingChartData.value = []
}

// 监听时间范围变化
watch(() => chartTimeRange.value, fetchRankingData, { immediate: true })

// 监听公司变化
watch(() => companyStore.currentCompany?.id, (newCompanyId) => {
    if (newCompanyId) {
        resetComponentState()
        // 如果有时间范围，则重新获取数据
        if (chartTimeRange.value) {
            fetchRankingData()
        }
    }
})

// 监听选中用途变化
watch([() => selectedSubCategory.value, () => chartTimeRange.value], getSubCategoryData, { immediate: true })

// 趋势图配置
const chartOptions = computed(() => ({
    xAxisData: chartData.value?.map(item => item.time) || [],
    yAxisUnit: 'kWh',
    series: [
        {
            name: '用电量',
            type: 'line',
            data: chartData.value?.map(item => item.value) || [],
        }
    ],
    customColors: ['#409EFF', '#909399']
}))
</script>

<template>
    <div class="card-header">
        <span>{{ title }}</span>
        <div class="right-content">
            <el-select style="width:35%;" filterable size="small" v-model="selectedSubCategory">
                <el-option v-for="item in rankingChartData.filter(item => item.name !== '其他')" :key="item.subcategory"
                    :label="item.name" :value="item.subcategory"></el-option>
            </el-select>
            <CustomDateRadio :isFragmentation="true" @update:modelValue="chartTimeRange = $event"></CustomDateRadio>
        </div>
    </div>
    <BaseChart :options="chartOptions" :height="height" />
</template>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.right-content {
    display: flex;
    align-items: center;
    gap: 8px;
}
</style>